//
//  PostWindowController.m
//  QuickPost
//
//  Created by Chen Xianan on 2/3/09.
//  Copyright 2009 sk. All rights reserved.
//

#import "PostWindowController.h"
#import "PostWindow.h"
#import "AppController.h"
#import "NSData+Base64.h"

@implementation PostWindowController

- (id)init
{
	if (self = [super initWithWindowNibName:@"Post"])
		return self;

	return nil;
}

- (void)dealloc
{
	[icons release];
	[super dealloc];
}

- (void)windowDidLoad
{
	PostWindow *win = [[PostWindow alloc] initWithView:_view];
	[self setWindow:win];
	[win release];
	[textarea setDelegate:self];
	NSMutableArray *cells = [NSMutableArray array];
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSArray *accounts = [defaults arrayForKey:QP_ACCOUNTS_KEY];
	icons = [[NSMatrix alloc] initWithFrame:NSMakeRect(20.0, 0.0, 16.0, 16.0)
									   mode:NSHighlightModeMatrix
								  cellClass:[NSImageCell class]
							   numberOfRows:1
							numberOfColumns:[accounts count]];
	[icons setCellSize:NSMakeSize(16.0, 16.0)];
	[icons setIntercellSpacing:NSMakeSize(4.0, 4.0)];
	[_view addSubview:icons];
	
	for (NSArray *acc in accounts){
		NSString *path = [[NSBundle mainBundle] pathForResource:[acc objectAtIndex:0]
														 ofType:@"ico"];
		NSImage *img = [[NSImage alloc] initWithContentsOfFile:path];
		NSImageCell *cell = [[NSImageCell alloc] initImageCell:img];
		[cells addObject:cell];
		[img release];
		[cell release];
	}
	[icons insertRow:0 withCells:cells];
	[icons sizeToCells];
}

- (void)post:(NSString *)body
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSArray *services = [defaults arrayForKey:QP_ACCOUNTS_KEY];
	if ([services count] == 0){	// TODO: how to show pref window?
		
	} else {
		for (NSArray *serv in services){
			[self connectionWithItem:serv
						 bodyContent:body];
		}
	}
}

- (void)connectionWithItem:(NSArray *)item
			   bodyContent:(NSString *)body
{
	//(0.service, 1.url, 2.field, 3.account, 4.password)
	NSString *format;
	if ([[item objectAtIndex:0] isEqualToString:@"HelloTxt"]){
		format = @"%@=%@&user_key=rAuc5IdQnK&app_key=pjtLUtC4xDgRb4o1";
	} else {
		format = @"%@=%@&source=QuickPostBar";
	}

	NSString *bodyString = [[NSString alloc]
								   initWithFormat:format,
							  [item objectAtIndex:2],
							   [body stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
	NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
	NSURL *url = [[NSURL alloc] initWithString:[item objectAtIndex:1]];
	NSString *authStr = [[NSString alloc] initWithFormat:@"%@:%@",
									 [item objectAtIndex:3],
									 [item objectAtIndex:4]];
	NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
	NSString *authValue = [[NSString alloc] initWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:80]];
	NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
	[req setHTTPMethod:@"POST"];
	[req setHTTPShouldHandleCookies:NO];
	[req setHTTPBody:bodyData];
	[req setValue:authValue forHTTPHeaderField:@"Authorization"];
	NSURLConnection *con = [[NSURLConnection alloc]
							   initWithRequest:req
									  delegate:self
							  startImmediately:YES];
	
	[bodyString release];
	[url release];
	[authStr release];
	[authValue release];
	[req release];
	[con release];
}

#pragma mark NSTextfield delegate
- (void)controlTextDidChange:(NSNotification *)aNotification
{
	NSNumber *num = [[NSNumber alloc] initWithUnsignedInteger:[[textarea stringValue] length]];
	[numchars setStringValue:[num stringValue]];
	[num release];
}

- (void)controlTextDidEndEditing:(NSNotification *)aNotification
{
	NSNumber *textMovement = [[aNotification userInfo] valueForKey:@"NSTextMovement"];
	if ([textMovement intValue] == 16){
		[self post:[textarea stringValue]];
	}
}

#pragma mark NSURLConnection delegate

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
	NSLog(@"error:%@", error);
}

- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSHTTPURLResponse *)response
{
	NSLog(@"response:%d", [response statusCode]);
}

- (void)connection:(NSURLConnection *)connection
	didReceiveData:(NSData *)data
{
	NSString *s = [[NSString alloc] initWithData:data
										encoding:NSUTF8StringEncoding];
	NSLog(@"data:%@", s);
	[s release];
}
@end
